const Promise = require('bluebird');


/**
 * 如何使用
 */
let articlesJson;
exports.howToUse = function ({user}, {models: {Users}, cache: {settings}, config}) {
    if (!articlesJson) {
        articlesJson = require(config.paths.json + 'articles.json');
    }
    return Users.findOne({
        where: {id: user && user.agency_id || 1},
        attributes: ['id', 'partner_id', 'order_return_scale']
    }).then(function (agency) {
        let redirectUrl;
        if (agency && agency.order_return_scale > 0) {
            redirectUrl = articlesJson[agency.partner_id] && articlesJson[agency.partner_id]['howToUse_hasReturn'];
            if (!redirectUrl) {
                redirectUrl = articlesJson[1] && articlesJson[1]['howToUse_hasReturn'];
            }
        } else {
            redirectUrl = articlesJson[agency.partner_id] && articlesJson[agency.partner_id]['howToUse_noReturn'];
            if (!redirectUrl) {
                redirectUrl = articlesJson[1] && articlesJson[1]['howToUse_noReturn'];
            }
        }
        return {redirect: redirectUrl};
    });
}

/**
 * 登录
 */
exports.login = function ({user}, {cache: {settings}}) {
    if (user) {
        return {redirect: '/user_center'};
    }
    return {
        title: '登录',
        layout: 'front/layouts/white',
        page: 'login',
        user: user,
        settings: settings.values()
    };
}

/**
 * 重置密码
 */
exports.forgot = function ({user}, {cache: {settings}}) {
    if (user) {
        return {redirect: '/user_center'};
    }
    return {
        title: '重置密码',
        layout: 'front/layouts/white',
        page: 'forgot',
        user: user,
        settings: settings.values()
    };
}

/**
 * 注册
 */
exports.register = function ({user}, {cache: {settings}}) {
    if (user) {
        return {redirect: '/user_center'};
    }
    return {
        title: '注册',
        layout: 'front/layouts/white',
        page: 'register',
        user: user,
        settings: settings.values()
    };
}

/**
 * 首页
 */
exports.index = function ({query, user, req}, {modelsData: {Categories, Goodses}, models: {Users}, cache: {settings}, redis, wechatInstance, config}) {
    return redis.cache('front_categories', 60 * 60 * 24, function () {
        return Categories.findAll({
            where: {level: 1, status: 'Active'},
            order: [['order_by', 'asc'], ['id', 'asc']],
            attributes: ['id', 'name'],
            raw: true
        });
    }).then(function (categories) {
        let data = {
            title: settings.value('title') + '-淘宝天猫优惠券领取与查找平台',
            layout: 'front/layouts/main',
            page: 'index',
            user: user,
            query: query,
            settings: settings.values(),
            categories: categories,
            shareUrl: config.domain + ((user && user.id) ? ('?inviter_id=' + user.id) : ''),
            show_qrcode: (user && user.subscribe) ? 0 : 1
        };
        let domain = req.hostname;
        // console.log('domain', domain, config.domain);
        if (config.domain.indexOf('http://' + domain) == -1) {
            return Users.findOne({where: {domain: domain}, attributes: ['id', 'banner']}).then(function (agency) {
                data.qrcode = agency && agency.banner || '';
                return data;
            });
        }

        return data;
    });
}

/**
 * 详情页
 */
exports.detail = function ({query, user, req}, {modelsData: {Goodses}, models: {Users, UsersViews, AgencysCoupons}, cache: {settings}, spider, config}) {
    let {id} = query;
    if (!id) {
        return {success: false, message: '参数错误'};
    }
    return spider.getGoodsByAuctionId({id: id, user_id: user && user.id}).then(function (goods) {
        if (!goods || goods.status != 'Active') {
            console.error('未找到商品', id, goods);
            return {redirect: '/'};
        }
        if (user) {
            let referer = req.headers && req.headers.referer || '';
            let source = referer.replace(config.domain, '').substr(0, 99);

            UsersViews.destroy({where: {goods_id: id, user_id: user.id}}).then(function () {
                return UsersViews.create({goods_id: id, user_id: user.id, agency_id: user.agency_id, source: source});
            }).catch(function (err) {
                console.error('详情页异常', {goods_id: id, user_id: user.id, agency_id: user.agency_id, source: source});
            });
        }

        return new Promise(function (resolve) {
            if (user && (user.level == 'Partner' || user.level == 'Agency')) {
                spider.applyCampaign({goods: goods, agency: user});
                return resolve(user);
            } else {
                let hanlder = function () {
                    return Users.findOne({where: {id: user && user.agency_id || 1}}).then(function (agency) {
                        spider.applyCampaign({goods: goods, agency: agency});
                        return resolve(agency);
                    });
                }

                if (!user) {
                    let domain = req.hostname;
                    let inviter_id = req.session.inviter_id;

                    // console.log('domain', domain);
                    return Users.findOne({where: {$or: {domain: domain, id: inviter_id}}}).then(function (agency) {
                        if (agency) {
                            if (agency.domain_pid) {
                                agency.pid = agency.domain_pid;
                            }

                            spider.applyCampaign({goods: goods, agency: agency});
                            return resolve(agency);
                        }

                        return hanlder();
                    });
                }

                return hanlder();
            }
        }).then(function (agency) {
            return AgencysCoupons.findOne({
                where: {agency_pid: agency && agency.pid || config.pid, goods_id: id},
                attributes: ['id', 'couponLink']
            }).then(function (agencysCoupon) {
                let price = goods.quanPrice || goods.zkPrice;
                let rate = goods.commission || goods.tkRate;
                let fee = (price * rate / 100);
                return {
                    title: settings.value('title') + '-' + goods.title,
                    layout: 'front/layouts/main',
                    page: 'detail',
                    user: user,
                    agency: agency,
                    userFanli: spider.getUserFanli({
                        fee: fee,
                        agency: agency
                    }),
                    agencyIncome: user && (user.level == 'Partner' || user.level == 'Agency') ? spider.getAgencyIncome({
                        fee: fee,
                        agency: agency
                    }) : 0,
                    agencysCoupon: agencysCoupon,
                    settings: settings.values(),
                    goods: goods,
                    pid: agency && agency.pid || config.pid,
                    shareUrl: config.domain + '/detail?id=' + id + '&inviter_id=' + (user ? user.id : '')
                };
            });
        });
    });
}

/**
 * 用户中心
 */
exports.userCenter = function ({query, user, user_id}, {models: {Users, TaokeOrders}, cache: {settings, dicts}}) {
    let data = {
        title: '用户中心',
        layout: 'front/layouts/main',
        page: 'user_center',
        user: user,
        settings: settings.values()
    };
    return Promise.props({
        user: Users.findOne({where: {id: user_id}})
    }).then(function ({user}) {
        if (user) {
            data.user = user;
            if (user.level == 'Partner') {
                data.is_partner = true;
            }
            if (user.level == 'Partner' || user.level == 'Agency') {
                data.is_agency = true;
            }
            user.level_dict = dicts.data('user_level', user.level);

            if (data.is_agency) {
                if (user.order_return_scale > 0) {
                    data.is_return = true;
                }
                return Promise.props({
                    fans_count: Users.count({
                        where: {
                            $or: {
                                inviter_id: user.id,
                                agency_id: user.id
                            }
                        }
                    }),
                    fans_orders_count: TaokeOrders.count({
                        where: {agency_id: user.id, payStatus: ['订单付款', '订单收货', '订单结算']}
                    }),
                    agency_frozen: (user.level == 'Partner' || user.level == 'Agency') ? TaokeOrders.agencyFrozenV2(user.id) : {}
                }).then(function ({fans_count, fans_orders_count, agency_frozen}) {
                    data.fans_count = fans_count;
                    data.fans_orders_count = fans_orders_count;

                    let agency_frozen_amount = 0;
                    let {agency, inviter_agency} = agency_frozen;
                    if (agency) {
                        agency_frozen_amount += agency.amount;
                    }
                    if (inviter_agency) {
                        agency_frozen_amount += inviter_agency.amount;
                    }
                    data.agency_frozen_amount = agency_frozen_amount;
                });
            } else {
                return Users.findOne({where: {id: (user.agency_id || 1)}}).then(function (agency) {
                    if (agency.order_return_scale > 0) {
                        data.is_return = true;
                    }
                });
            }
        }
    }).then(function () {
        data.show_amount = data.is_agency || data.is_return;
        return data;
    });
}

/**
 * 编辑用户信息
 */
exports.userEdit = function ({query, user, user_id}, {models: {Users}, cache: {settings, dicts}}) {
    let data = {
        title: '编辑用户信息',
        layout: 'front/layouts/main',
        page: 'user_edit',
        user: user,
        settings: settings.values()
    };
    return Users.findOne({where: {id: user_id}}).then(function (user) {
        data.user = user;
        return data;
    });
}

/**
 * 申请提现
 */
exports.withdrawApply = function ({query, user_id}, {models: {Users}, cache: {settings, dicts}}) {
    return Users.findOne({where: {id: user_id}}).then(function (user) {
        if (user.level == 'Partner') {
            return {user: user, partner: user};
        }
        return Users.findOne({where: {id: user.partner_id || 1}}).then(function (partner) {
            return {user: user, partner: partner};
        });
    }).then(function ({user, partner}) {
        if (user.bank_type) {
            user.bank_type_dict = dicts.data('bank_type', user.bank_type);
        }
        return {
            title: '申请提现',
            layout: 'front/layouts/main',
            page: 'withdraw_apply',
            settings: settings.values(),
            user: user,
            partner: partner
        };
    });
}

/**
 * 设置提现账号
 */
exports.bankEdit = function ({query, user_id}, {models: {Users}, cache: {settings, dicts}}) {
    return Users.findOne({where: {id: user_id}}).then(function (user) {
        return {
            title: '设置提现账号',
            layout: 'front/layouts/main',
            page: 'bank_edit',
            settings: settings.values(),
            user: user,
            banks: dicts.group('bank_type')
        };
    });
}

/**
 * 收支明细
 */
exports.finances = function ({query, user}, {models: {UsersFinances}, cache: {settings, dicts}, controller}) {
    query.user_id = user.id;
    query.limit = 20;
    query.type = ['In', 'Out'];
    return UsersFinances.findAndCountAll(controller.pagination({
        params: query,
        filters: ['user_id', 'type', 'status'],
        likes: ['order_id'],
        order: [['id', 'desc']]
    })).then(function ({rows, count}) {
        for (let i in rows) {
            let finance = rows[i];
            finance.operation_dict = dicts.data('finance_operation', finance.operation);
        }
        let data = {
            title: '收支明细',
            layout: 'front/layouts/main',
            page: 'finances',
            settings: settings.values(),
            user: user,
            finances: rows
        };
        if (count > query.limit + parseInt(query.offset || 0)) {
            data.loadmore = true;
        }
        return data;
    });
}

/**
 * 用户收支明细
 */
exports.userFinances = function ({query, user}, {models: {Users, UsersFinances}, cache: {settings, dicts}, controller}) {
    let {user_id} = query;
    if (!user_id) {
        return {success: false, message: '参数错误'};
    }
    return Users.findOne({where: {id: user_id, partner_id: user.id}}).then(function (u) {
        if (!u) {
            return {success: false, message: '用户不存在'};
        }
        query.limit = 20;
        query.type = ['In', 'Out'];
        return UsersFinances.findAndCountAll(controller.pagination({
            params: query,
            filters: ['user_id', 'type', 'status'],
            likes: ['order_id'],
            order: [['id', 'desc']]
        })).then(function ({rows, count}) {
            for (let i in rows) {
                let finance = rows[i];
                finance.operation_dict = dicts.data('finance_operation', finance.operation);
            }
            let data = {
                title: '收支明细',
                layout: 'front/layouts/main',
                page: 'user_finances',
                settings: settings.values(),
                user_id: user_id,
                user: u,
                finances: rows
            };
            if (count > query.limit + parseInt(query.offset || 0)) {
                data.loadmore = true;
            }
            return data;
        });
    });
}

/**
 * 提现记录
 */
exports.withdraws = function ({query, user}, {models: {UsersWithdraws}, cache: {settings, dicts}, controller}) {
    query.user_id = user.id;
    query.limit = 20;
    return UsersWithdraws.findAndCountAll(controller.pagination({
        params: query,
        filters: ['user_id', 'is_virtual', 'status'],
        likes: ['trade_no'],
        order: [['id', 'desc']]
    })).then(function ({rows, count}) {
        for (let i in rows) {
            let withdraw = rows[i];
            withdraw.status_dict = dicts.data('withdraw_status', withdraw.status);
        }
        let data = {
            title: '提现记录',
            layout: 'front/layouts/main',
            page: 'withdraws',
            settings: settings.values(),
            user: user,
            withdraws: rows
        };
        if (count > query.limit + parseInt(query.offset || 0)) {
            data.loadmore = true;
        }
        return data;
    });
}

/**
 * 用户提现记录
 */
exports.userWithdraws = function ({query, user}, {models: {Users, UsersWithdraws}, cache: {settings, dicts}, controller}) {
    let {user_id} = query;
    if (!user_id) {
        return {success: false, message: '参数错误'};
    }
    return Users.findOne({where: {id: user_id, partner_id: user.id}}).then(function (u) {
        if (!u) {
            return {success: false, message: '用户不存在'};
        }
        query.limit = 20;
        return UsersWithdraws.findAndCountAll(controller.pagination({
            params: query,
            filters: ['user_id', 'is_virtual', 'status'],
            likes: ['trade_no'],
            order: [['id', 'desc']]
        })).then(function ({rows, count}) {
            for (let i in rows) {
                let withdraw = rows[i];
                withdraw.status_dict = dicts.data('withdraw_status', withdraw.status);
            }
            let data = {
                title: '提现记录',
                layout: 'front/layouts/main',
                page: 'user_withdraws',
                settings: settings.values(),
                user_id: user_id,
                user: u,
                withdraws: rows
            };
            if (count > query.limit + parseInt(query.offset || 0)) {
                data.loadmore = true;
            }
            return data;
        });
    });
}

/**
 * 提现管理
 */
exports.partnerWithdraws = function ({query, user}, {models: {Users, UsersWithdraws, associations}, cache: {settings, dicts}, controller}) {
    query.limit = 20;
    query.partner_id = user.id;
    if (!query.status) {
        query.status = 'all';
    }
    let pagination = controller.pagination({
        params: query,
        filters: ['id', 'partner_id', 'user_id', 'bank_type', 'bank_tel', 'status'],
        likes: ['user_id', 'trade_no', 'bank_name', 'bank_no', 'bank_tel'],
        order: [['id', 'desc']]
    });
    return UsersWithdraws.findAndCountAll(pagination).then(function (data) {
        return associations.relateOne(data, Users, 'user_id', 'user', ['id', 'image', 'nickname', 'username', 'nickname', 'tel', 'level', 'order_count', 'finish_count', 'sham_count', 'amount', 'frozen']);
    }).then(function ({rows, count}) {
        for (let i in rows) {
            let row = rows[i];
            row.level_dict = dicts.data('user_level', row.user.level);
            row.bank_type_dict = dicts.data('bank_type', row.bank_type);
            row.status_dict = dicts.data('withdraw_status', row.status);
        }
        let data = {
            title: '提现管理',
            layout: 'front/layouts/main',
            page: 'partner_withdraws',
            settings: settings.values(),
            query: query,
            rows: rows
        };
        if (count > query.limit + parseInt(query.offset || 0)) {
            data.loadmore = true;
        }
        return data;
    });
}

/**
 * 用户管理
 */
exports.partnerUsers = function ({query, user}, {models: {Users, associations}, cache: {settings, dicts}, controller}) {
    query.limit = 20;
    query.partner_id = user.id;
    if (!query.order_by) {
        query.order_by = 'id-desc';
    }
    let orderArr = query.order_by.split('-');
    let pagination = controller.pagination({
        params: query,
        filters: ['level', 'role', 'inviter_id', 'partner_id', 'agency_id', 'subscribe', 'sex', 'status'],
        likes: ['id', 'tel', 'username', 'nickname', 'email', 'qq'],
        order: [[orderArr[0], orderArr[1]]]
    });
    return Users.findAndCountAll(pagination).then(function (data) {
        return associations.relateOne(data, Users, 'inviter_id', 'inviter_user', ['id', 'image', 'username', 'nickname', 'tel']);
    }).then(function (data) {
        return associations.relateOne(data, Users, 'agency_id', 'agency_user', ['id', 'image', 'username', 'nickname', 'tel']);
    }).then(function ({rows, count}) {
        for (let i in rows) {
            let row = rows[i];
            row.level_dict = dicts.data('user_level', row.level);
        }
        let data = {
            title: '用户管理',
            layout: 'front/layouts/main',
            page: 'partner_users',
            settings: settings.values(),
            rows: rows,
            query: query
        };
        if (count > query.limit + parseInt(query.offset || 0)) {
            data.loadmore = true;
        }
        return data;
    });
}

/**
 * 结算管理
 */
exports.partnerSettles = function ({query, user}, {models: {Users, AgencysSettles, associations}, cache: {settings, dicts}, controller}) {
    query.limit = 20;
    query.partner_id = user.id;
    let pagination = controller.pagination({
        params: query,
        filters: ['partner_id', 'agency_id', 'inviter_agency_id'],
        order: [['id', 'desc']]
    });
    return AgencysSettles.findAndCountAll(pagination).then(function (data) {
        return associations.relateOne(data, Users, 'agency_id', 'agency', ['id', 'image', 'username', 'nickname', 'tel']);
    }).then(function (data) {
        return associations.relateOne(data, Users, 'inviter_agency_id', 'inviterAgency', ['id', 'image', 'username', 'nickname', 'tel']);
    }).then(function ({rows, count}) {
        for (let i in rows) {
            let row = rows[i];
            if (row.is_amount) {
                row.statusName = '已入账';
            } else if (row.is_payed) {
                row.statusName = '已支付';
            }
            row.hasOpt = (!row.is_amount && !row.is_payed);
        }
        let data = {
            title: '结算管理',
            layout: 'front/layouts/main',
            page: 'partner_settles',
            settings: settings.values(),
            user: user,
            rows: rows
        };
        if (count > query.limit + parseInt(query.offset || 0)) {
            data.loadmore = true;
        }
        return data;
    });
}

/**
 * 返现状态
 */
let setAmountStatus = function (item) {
    let amountStatus;
    if (item.is_back) {
        amountStatus = '已退回';
    } else if (item.is_payed) {
        amountStatus = '已支付';
    } else if (item.is_settle) {
        amountStatus = '已结算';
    } else if (item.is_amount) {
        amountStatus = '已入账';
    } else {
        amountStatus = '待入账';
    }
    item.amount_status = amountStatus;
}

/**
 * 代理管理
 */
exports.partnerAgency = function ({query, user}, {models: {Users, TaokeOrders}, cache: {settings, dicts}, controller}) {
    query.limit = 20;
    query.partner_id = user.id;
    query.level = ['Agency', 'Partner'];

    if (!query.order_by) {
        query.order_by = 'id-desc';
    }
    let orderArr = query.order_by.split('-');

    let pagination = controller.pagination({
        params: query,
        filters: ['id', 'inviter_id', 'agency_id', 'partner_id', 'level'],
        likes: ['id', 'tel', 'nickname'],
        order: [[orderArr[0], orderArr[1]]]
    });
    return Users.findAndCountAll(pagination).then(function (result) {
        let rows = result.rows;
        if (rows && rows.length) {
            return Promise.mapSeries(rows, function (row) {
                return TaokeOrders.analyseV2({agency_id: row.id}).then(function (data) {
                    row.data = data;
                    return Users.count({
                        where: {
                            $or: {
                                agency_id: row.id,
                                inviter_id: row.id
                            }
                        }
                    }).then(function (count) {
                        row.data.fans_count = count;
                    });
                });
            }).then(function () {
                return result;
            });
        }
        return result;
    }).then(function ({rows, count}) {
        for (let i in rows) {
            let inviter = rows[i];
            inviter.level_dict = dicts.data('user_level', inviter.level);
        }
        let data = {
            title: '代理管理',
            layout: 'front/layouts/main',
            page: 'partner_agency',
            settings: settings.values(),
            user: user,
            rows: rows,
            query: query
        };
        if (count > query.limit + parseInt(query.offset || 0)) {
            data.loadmore = true;
        }
        return data;
    });
}

/**
 * 我的粉丝
 */
exports.fansList = function ({query, user}, {models: {Users, TaokeOrders}, cache: {settings, dicts}, controller}) {
    query.limit = 20;
    let pagination = controller.pagination({
        params: query,
        filters: ['inviter_id', 'agency_id', 'level'],
        likes: ['id', 'tel', 'nickname'],
        order: [['id', 'desc']]
    });
    if (pagination.where.$or) {
        pagination.where.agency_id = user.id;
    } else {
        pagination.where.$or = {
            inviter_id: user.id,
            agency_id: user.id
        };
    }
    return Users.findAndCountAll(pagination).then(function (result) {
        let rows = result.rows;
        if (rows && rows.length) {
            return Promise.mapSeries(rows, function (row) {
                if (row.level == 'Agency') {
                    return TaokeOrders.analyseV2({agency_id: row.id}).then(function (data) {
                        row.data = data;
                        return Users.count({
                            where: {
                                $or: {
                                    agency_id: row.id,
                                    inviter_id: row.id
                                }
                            }
                        }).then(function (count) {
                            row.data.fans_count = count;
                        });
                    });
                }
            }).then(function () {
                return result;
            });
        }
        return result;
    }).then(function ({rows, count}) {
        for (let i in rows) {
            let inviter = rows[i];
            inviter.level_dict = dicts.data('user_level', inviter.level);
        }
        if (!query.level) {
            query.level = 'all';
        }
        let data = {
            title: '我的粉丝',
            layout: 'front/layouts/main',
            page: 'fans_list',
            settings: settings.values(),
            user: user,
            rows: rows,
            query: query
        };
        if (count > query.limit + parseInt(query.offset || 0)) {
            data.loadmore = true;
        }
        return data;
    });
}

/**
 * 合伙人订单
 */
exports.partnerOrders = function ({query, user}, {models: {TaokeOrders, JDOrders, Users, associations}, cache: {settings, dicts}, controller}) {
    let status = query.status, orderBy;
    if (!status) {
        query.status = 'All';
    }
    query.limit = 20;

    let handle = function () {
        if (query.type === 'jd') {
            if (status == 'Active') {
                query.orderStatusName = ['已完成', '等待发货', '等待出库', '等待确认收货'];
            } else if (status == 'Deactivated') {
                query.orderStatusName = ['等待付款', '锁定'];
            } else if (status == 'Settle') {
                query.orderStatusName = ['已完成'];
            }
            query.partner_id = user.id;

            let pagination = controller.pagination({
                params: query,
                filters: ['orderId', 'spId', 'orderStatus', 'orderStatusName', 'agency_id', 'user_id', 'is_payed', 'is_back', 'agency_settle_id'],
                likes: ['orderId', 'spId', 'user_id'],
                order: orderBy || [['orderDate', 'desc']]
            });

            return JDOrders.findAndCountAll(pagination);
        }

        if (status == 'Active') {
            query.payStatus = ['订单付款', '订单收货', '订单结算'];
        } else if (status == 'Deactivated') {
            query.payStatus = ['订单失效'];
        } else if (status == 'Settle') {
            orderBy = [['earningTime', 'desc']];
            query.payStatus = ['订单结算'];
        }
        let pagination = controller.pagination({
            params: query,
            filters: ['exMemberId', 'shopTitle', 'payStatus', 'terminalType', 'adPositionId', 'mediumId', 'agency_id', 'user_id', 'is_payed', 'is_back', 'taobaoTradeParentId', 'agency_settle_id'],
            likes: ['taobaoTradeParentId', 'adPositionId', 'user_id'],
            order: orderBy || [['createTime', 'desc']]
        });
        if (pagination.where.$or) {
            pagination.where.tao_user = user.tao_user;
        } else {
            pagination.where.$or = {
                partner_id: user.id,
                tao_user: user.tao_user
            }
        }
        return TaokeOrders.findAndCountAll(pagination);
    }


    return handle().then(function (data) {
        return associations.relateOne(data, Users, 'user_id', 'user', ['id', 'image', 'username', 'nickname', 'tel', 'order_count', 'finish_count', 'sham_count', 'amount', 'frozen']);
    }).then(function (data) {
        return associations.relateOne(data, Users, 'agency_id', 'agency', ['id', 'image', 'username', 'nickname', 'tel']);
    }).then(function ({rows, count}) {
        for (let i in rows) {
            let row = rows[i];
            if (row.skus) {
                row.skus = JSON.parse(row.skus);
            }
            if (row.feeString > 0) {
                row.income = (parseFloat(row.feeString || 0) * 0.9 - parseFloat(row.pay_amount || 0) - parseFloat(row.agency_amount || 0) - parseFloat(row.inviter_pay_amount || 0) - parseFloat(row.inviter_agency_amount || 0)).toFixed(2);
            } else {
                row.income = 0;
            }

            setAmountStatus(row);

            if (query.type == 'jd') {

            } else {
                row.hasPayed = TaokeOrders.payedCheck(row);
            }
        }

        if (!query.keyword) {
            query.keyword = query.taobaoTradeParentId || query.orderId || query.agency_id || query.mediumId || query.adPositionId || query.spId || query.user_id || query.agency_settle_id || '';
        }
        let data = {
            title: '合伙人订单',
            layout: 'front/layouts/main',
            page: 'partner_orders',
            settings: settings.values(),
            user: user,
            rows: rows,
            query: query
        };
        if (count > query.limit + parseInt(query.offset || 0)) {
            data.loadmore = true;
        }
        return data;
    });
}

/**
 * 粉丝订单
 */
exports.fansOrders = function ({query, user}, {models: {TaokeOrders}, cache: {settings, dicts}, controller}) {
    let status = query.status;
    if (!status) {
        query.status = 'All';
    }
    if (status == 'Active') {
        query.payStatus = ['订单付款', '订单收货', '订单结算'];
    } else if (status == 'Deactivated') {
        query.payStatus = ['订单失效'];
    }

    query.agency_id = user.id;
    query.limit = 20;
    return TaokeOrders.findAndCountAll(controller.pagination({
        params: query,
        filters: ['exMemberId', 'shopTitle', 'payStatus', 'terminalType', 'adPositionId', 'mediumId', 'username', 'user_id', 'agency_id', 'is_payed', 'is_back', 'taobaoTradeParentId'],
        likes: ['auctionId', 'auctionTitle', 'nickname', 'taobaoTradeParentId'],
        order: [['createTime', 'desc']]
    })).then(function ({rows, count}) {
        for (let i in rows) {
            let row = rows[i];
            setAmountStatus(row);
        }

        let data = {
            title: '粉丝订单',
            layout: 'front/layouts/main',
            page: 'fans_orders',
            settings: settings.values(),
            user: user,
            rows: rows,
            query: query
        };
        if (count > query.limit + parseInt(query.offset || 0)) {
            data.loadmore = true;
        }
        return data;
    });
}

/**
 * 我的订单
 */
exports.myOrders = function ({query, user}, {models: {Users, TaokeOrders, JDOrders, UserOrders, JDUserOrders, associations}, cache: {settings, dicts}, controller}) {
    query.user_id = user.id;
    query.limit = 20;
    if (!query.status) {
        query.status = {$ne: 'Delete'};
    }
    let handle = function () {
        if (query.type === 'jd') {
            return JDUserOrders.findAndCountAll(controller.pagination({
                params: query,
                filters: ['user_id', 'orderId', 'status'],
                likes: ['orderId'],
                order: [['id', 'desc']]
            })).then(function (data) {
                let rows = data.rows, ids = [];
                if (rows && rows.length) {
                    for (let i in rows) {
                        let row = rows[i];
                        if (row.orderId) {
                            ids.push(row.orderId);
                        }
                    }
                    if (ids.length) {
                        return JDOrders.findAll({
                            where: {orderId: ids},
                            raw: true
                        }).then(function (items) {
                            let map = {};
                            for (let i in items) {
                                let item = items[i];
                                if (item.skus) {
                                    item.skus = JSON.parse(item.skus);
                                }
                                setAmountStatus(item);

                                map[item.orderId] = item;
                            }
                            for (let i in rows) {
                                let row = rows[i];
                                row.jdOrder = map[row.orderId];
                            }
                            return data;
                        });
                    }
                }
                return data;
            });
        }
        return UserOrders.findAndCountAll(controller.pagination({
            params: query,
            filters: ['user_id', 'taobaoTradeParentId', 'status'],
            likes: ['taobaoTradeParentId'],
            order: [['id', 'desc']]
        })).then(function (data) {
            let rows = data.rows, ids = [];
            if (rows && rows.length) {
                for (let i in rows) {
                    let row = rows[i];
                    if (row.taobaoTradeParentId) {
                        ids.push(row.taobaoTradeParentId);
                    }
                }
                if (ids.length) {
                    return TaokeOrders.findAll({
                        where: {taobaoTradeParentId: ids},
                        raw: true
                    }).then(function (items) {
                        let map = {};
                        for (let i in items) {
                            let item = items[i];
                            setAmountStatus(item);

                            if (map[item.taobaoTradeParentId]) {
                                map[item.taobaoTradeParentId].push(item);
                            } else {
                                map[item.taobaoTradeParentId] = [item];
                            }
                        }
                        for (let i in rows) {
                            let row = rows[i];
                            row.taokeOrders = map[row.taobaoTradeParentId]
                        }
                        return data;
                    });
                }
            }
            return data;
        });
    }

    return handle().then(function ({rows, count}) {
        return Users.findOne({where: {id: user.partner_id || 1}}).then(function (partner) {
            let data = {
                title: '我的订单',
                layout: 'front/layouts/main',
                page: 'my_orders',
                settings: settings.values(),
                partner: partner,
                user: user,
                rows: rows,
                query: query
            };
            if (count > query.limit + parseInt(query.offset || 0)) {
                data.loadmore = true;
            }
            return data;
        });
    });
}

/**
 * 浏览记录
 */
exports.goodsesViews = function ({query, user}, {models: {}, cache: {settings, dicts}, controller}) {
    let data = {
        title: '浏览记录',
        layout: 'front/layouts/main',
        page: 'goodses_views',
        settings: settings.values(),
        user: user
    };

    return data;
}


/**
 * 搜索记录
 */
exports.goodsesSearchs = function ({query, user}, {models: {}, cache: {settings, dicts}, controller}) {
    let data = {
        title: '搜索记录',
        layout: 'front/layouts/main',
        page: 'goodses_searchs',
        settings: settings.values(),
        user: user
    };

    return data;
}

/**
 * 建议反馈
 */
exports.suggestions = function ({query, user}, {models: {Suggestions}, cache: {settings}}) {
    return {
        title: '建议反馈',
        layout: 'front/layouts/main',
        page: 'suggestions',
        settings: settings.values(),
        user: user
    };
}

/**
 * 我的客服
 */
exports.customers = function ({query, user}, {models: {Articles}, cache: {settings}}) {
    return Articles.findOne({where: {slug: 'customers'}}).then(function (article) {
        return {
            title: '我的客服',
            layout: 'front/layouts/main',
            page: 'customers',
            settings: settings.values(),
            user: user,
            article: article
        };
    });
}

/**
 * 文章详情
 */
exports.article = function ({query, user}, {models: {Articles}, cache: {settings}}) {
    let {id, slug} = query;
    let where = {};
    if (id) {
        where.id = id;
    }
    if (slug) {
        where.slug = slug;
    }
    return Articles.findOne({where: where}).then(function (article) {
        if (article) {
            Articles.updateViewCountV2({id: article.id});
        }
        return {
            title: article.title,
            layout: 'front/layouts/main',
            page: 'article',
            settings: settings.values(),
            user: user,
            article: article
        };
    });
}

/**
 * 文章列表
 */
exports.articles = function ({query, user}, {models: {Articles}, cache: {settings}, controller}) {
    query.limit = 20;
    query.status = 'Active';
    return Articles.findAndCountAll(controller.pagination({
        params: query,
        filters: ['type', 'status'],
        likes: ['title'],
        attributes: ['id', 'title', 'description', 'content', 'image', 'created_at'],
        order: [['order_by', 'asc'], ['id', 'desc']]
    })).then(function ({count, rows}) {
        let data = {
            title: '历史文章',
            layout: 'front/layouts/main',
            page: 'articles',
            settings: settings.values(),
            user: user,
            articles: rows
        };
        if (count > query.limit + parseInt(query.offset || 0)) {
            data.loadmore = true;
        }
        return data;
    });
}

/**
 * 最近浏览
 */
exports.lastVisitors = function ({query, user, user_id}, {models: {Users, UsersViews, UsersSearchs, associations}, cache: {settings, dicts}}) {
    let {goods_id} = query;
    return Users.findOne({where: {id: user_id, level: 'Partner'}}).then(function (partner) {
        if (!partner) {
            return {success: false, messsage: '没有权限'};
        }
        return Promise.props({
            views: UsersViews.findAll({
                where: {goods_id: goods_id},
                order: [['id', 'desc']],
                limit: 10
            }).then(function (data) {
                return associations.relateOne(data, Users, 'user_id', 'user', ['id', 'image', 'username', 'nickname', 'tel', 'level', 'amount', 'frozen', 'order_count', 'finish_count', 'sham_count', 'created_at']);
            }).then(function (rows) {
                for (let i in rows) {
                    let view = rows[i];
                    view.user.level_dict = dicts.data('user_level', view.user.level);
                }
                return rows;
            }),
            searchs: UsersSearchs.findAll({
                where: {goods_id: goods_id},
                order: [['id', 'desc']],
                limit: 10
            }).then(function (data) {
                return associations.relateOne(data, Users, 'user_id', 'user', ['id', 'image', 'username', 'nickname', 'tel', 'level', 'amount', 'frozen', 'order_count', 'finish_count', 'sham_count', 'created_at']);
            }).then(function (rows) {
                for (let i in rows) {
                    let view = rows[i];
                    view.user.level_dict = dicts.data('user_level', view.user.level);
                }
                return rows;
            })
        }).then(function ({views, searchs}) {
            return {
                title: '最近浏览',
                layout: 'front/layouts/main',
                page: 'last_visitors',
                settings: settings.values(),
                user: user,
                views: views,
                searchs: searchs
            };
        });
    });
}

/**
 * 获取品牌
 */
exports.pinpai = function ({query, user, req}, {models: {Users}, cache: {settings}, config, redis, spider}) {
    return redis.cache('pinpai_goodses_cache', 60 * 20, function () {
        return spider.findPinPai();
    }).then(function (rows) {
        let data = {
            title: settings.value('title') + '-淘宝天猫优惠券领取与查找平台',
            layout: 'front/layouts/main',
            page: 'pinpai',
            user: user,
            query: query,
            rows: rows,
            classNames: 'browse-item',
            settings: settings.values(),
            shareUrl: config.domain + '/pinpai' + ((user && user.id) ? ('?inviter_id=' + user.id) : ''),
            show_qrcode: (user && user.subscribe) ? 0 : 1
        };

        let domain = req.hostname;
        // console.log('domain', domain, config.domain);
        if (config.domain.indexOf('http://' + domain) == -1) {
            return Users.findOne({where: {domain: domain}, attributes: ['id', 'banner']}).then(function (agency) {
                data.qrcode = agency && agency.banner || '';
                return data;
            });
        }

        return data;
    });
}

/**
 * 获取跑单
 */
exports.sales = function ({query, user, req}, {models: {Users}, cache: {settings}, config, redis, spider}) {
    return redis.cache('sales_goodses_cache', 60 * 20, function () {
        return spider.findSales();
    }).then(function (rows) {
        let data = {
            title: settings.value('title') + '-淘宝天猫优惠券领取与查找平台',
            layout: 'front/layouts/main',
            page: 'sales',
            user: user,
            query: query,
            rows: rows,
            classNames: 'browse-item',
            settings: settings.values(),
            shareUrl: config.domain + '/sales' + ((user && user.id) ? ('?inviter_id=' + user.id) : ''),
            show_qrcode: (user && user.subscribe) ? 0 : 1
        };

        let domain = req.hostname;
        // console.log('domain', domain, config.domain);
        if (config.domain.indexOf('http://' + domain) == -1) {
            return Users.findOne({where: {domain: domain}, attributes: ['id', 'banner']}).then(function (agency) {
                data.qrcode = agency && agency.banner || '';
                return data;
            });
        }

        return data;
    });
}

/**
 * 获取神单
 */
exports.shendan = function ({query, user, req}, {models: {Users}, cache: {settings}, config, redis, spider}) {
    return redis.cache('shendan_goodses_cache', 60 * 3, function () {
        return spider.findShenDan();
    }).then(function (rows) {
        let data = {
            title: settings.value('title') + '-淘宝天猫优惠券领取与查找平台',
            layout: 'front/layouts/main',
            page: 'shendan',
            user: user,
            query: query,
            rows: rows,
            classNames: 'browse-item',
            settings: settings.values(),
            shareUrl: config.domain + '/shendan' + ((user && user.id) ? ('?inviter_id=' + user.id) : ''),
            show_qrcode: (user && user.subscribe) ? 0 : 1
        };

        let domain = req.hostname;
        // console.log('domain', domain, config.domain);
        if (config.domain.indexOf('http://' + domain) == -1) {
            return Users.findOne({where: {domain: domain}, attributes: ['id', 'banner']}).then(function (agency) {
                data.qrcode = agency && agency.banner || '';
                return data;
            });
        }

        return data;
    });
}
